const mongoose = require('mongoose');
const config = require('../config/config');
const log = require('./log4js')('DB');

if (config.dbName === 'localTest') {
    mongoose.connect('mongodb://' + config.dbPath + config.dbName, { useNewUrlParser: true, useUnifiedTopology: true  });
} else {
    mongoose.connect(`mongodb://${config.dbName}:${config.dbPwd}@${config.dbPath}${config.dbName}`);
}

const db = mongoose.connection;

db.on('error', function (error) {
    log.error(`<<<<<<<<连接数据库${config.dbName}失败`);
    console.log(error);
    log.error(`连接数据库${config.dbName}失败>>>>>>`);
});

db.once('open', function () {
    log.info(`连接数据库${config.dbName}成功`);
});
db.on('disconnected', function () {
    log.warn(`数据库${config.dbName}断开连接`);
});

module.exports = db;
